<template>
  <div>
    <el-steps :active="active" finish-status="success" align-center>
      <el-step title="账号注册" />
      <el-step title="邮箱绑定" />
      <el-step title="个性化设置" />
    </el-steps>
    <div class="register-form">
      <el-form
        ref="registerForm"
        :model="registerFormData"
        :rules="registerRules"
        @keyup.enter="submitRegisterForm"
        style="width: 420px"
        v-if="active === 0"
      >
        <el-form-item prop="account">
          <el-input
            v-model="registerFormData.account"
            size="large"
            placeholder="请输入用户名"
            prefix-icon="User"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="registerFormData.password"
            show-password
            size="large"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            autocomplete="off"
            maxlength="16"
          />
        </el-form-item>
        <el-form-item prop="resetPassword">
          <el-input
            v-model="registerFormData.resetPassword"
            show-password
            size="large"
            type="password"
            placeholder="请重新输入密码"
            prefix-icon="Lock"
            autocomplete="off"
            maxlength="16"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            size="large"
            style="width: 100%"
            @click="submitRegisterForm"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>
      <el-form
        ref="registerEmailForm"
        :model="registerEmailFormData"
        :rules="emailRules"
        @keyup.enter="submitEmailForm"
        style="width: 420px"
        v-else-if="active === 1"
      >
        <el-form-item prop="email">
          <el-input
            type="email"
            v-model="registerEmailFormData.email"
            size="large"
            placeholder="请输入邮箱"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="captcha">
          <el-input
            v-model="registerEmailFormData.captcha"
            size="large"
            placeholder="请输入验证码"
            prefix-icon="CircleCheck"
          >
            <template #append>
              <el-button
                :disabled="countdown > 0"
                @click="getRegisterCaptcha()"
              >
                {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            size="large"
            style="width: 100%"
            @click="submitEmailForm"
          >
            绑定
          </el-button>
        </el-form-item>
      </el-form>
      <el-form
        ref="userDataForm"
        :model="userData"
        label-width="68px"
        style="width: 420px"
        :rules="infoRules"
        @keyup.enter="submitUserDataForm"
        v-else
      >
        <el-form-item label="头像" prop="avatar" required>
          <el-popover placement="right" :width="320" trigger="click">
            <template #reference>
              <el-avatar
                :size="80"
                :src="userData.avatar"
                style="cursor: pointer"
              />
            </template>
            <div style="display: flex">
              <div v-for="index in [1, 2, 3]">
                <el-avatar
                  :size="80"
                  :src="'male' + index + '.png'"
                  style="cursor: pointer"
                  @click="
                    () => {
                      userData.avatar = 'male' + index + '.png'
                    }
                  "
                />
                <el-avatar
                  :size="80"
                  :src="'female' + index + '.png'"
                  style="cursor: pointer"
                  @click="
                    () => {
                      userData.avatar = 'female' + index + '.png'
                    }
                  "
                />
              </div>
            </div>
          </el-popover>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname" required>
          <el-input
            v-model="userData.nickname"
            type="text"
            maxlength="20"
            placeholder="请输入昵称"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="个人介绍" prop="introduction">
          <el-input
            v-model="userData.introduction"
            type="textarea"
            maxlength="50"
            placeholder="请输入个人介绍"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="主题颜色">
          <el-color-picker
            @change="setColor"
            v-model="userData.colorTheme"
            size="small"
            show-alpha
            :predefine="config.predefineColors"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            size="large"
            style="width: 100%"
            @click="submitUserDataForm"
          >
            提交
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'Register',
}
</script>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import config from '@/setting'
import { ElMessage } from 'element-plus'
import { reqGetBindingEmailCaptcha } from '@/api/email'
import { SET_TOKEN } from '@/utils/token'
import { reqBindingEmail, reqUerRegister } from '@/api/auth'
import { reqAddUserInfo } from '@/api/user'
import useUserStore from '@/store/modules/user'
import router from '@/router'
//步骤条
const active = ref(0)
const countdown = ref(0)
const loading = ref(false)

//注册相关
let registerForm = ref()
const registerFormData = reactive({
  account: '',
  password: '',
  resetPassword: '',
})

let registerEmailForm = ref()
const registerEmailFormData = reactive({
  email: '',
  captcha: '',
})

let userDataForm = ref()
const userData = reactive({
  nickname: '',
  avatar: 'male1.png',
  introduction: '',
  colorTheme: config.defaultColor,
})

const userStore = useUserStore()
// 验证函数
const checkAccount = (rule: any, value: any, callback: any) => {
  if (value.length < 5 || value.length > 16) {
    return callback(new Error('请输入正确的用户名'))
  } else {
    callback()
  }
}
const checkPassword = (rule: any, value: any, callback: any) => {
  if (value.length < 6 || value.length > 16) {
    return callback(new Error('请输入6位到16位的密码'))
  } else {
    callback()
  }
}
const checkResetPassword = (rule: any, value: any, callback: any) => {
  if (value.length < 6 || value.length > 16) {
    return callback(new Error('请输入6位到16位的密码'))
  } else if (value !== registerFormData.password) {
    return callback(new Error('密码不一致'))
  } else {
    callback()
  }
}

const registerRules = reactive({
  account: [{ validator: checkAccount, trigger: 'blur' }],
  password: [{ validator: checkPassword, trigger: 'blur' }],
  resetPassword: [{ validator: checkResetPassword, trigger: 'blur' }],
})

const emailRules: any = reactive({
  email: [
    {
      required: true,
      type: 'email',
      message: '输入正确的邮箱',
      trigger: 'blur',
    },
  ],
  captcha: [
    { required: true, message: '输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '必须为六位验证码', trigger: 'blur' },
  ],
})

const infoRules: any = reactive({
  nickname: [
    {
      required: true,
      message: '请输入昵称',
      trigger: 'blur',
    },
  ],
})

const getRegisterCaptcha = async () => {
  await registerEmailForm.value.validateField('email')
  try {
    const { message } = await reqGetBindingEmailCaptcha(
      registerEmailFormData.email,
    )
    startTimer()
    ElMessage.success(message)
  } catch (error) {
    ElMessage({
      type: 'error',
      message: (error as Error).message,
    })
  }
}

const startTimer = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value === 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const submitRegisterForm = async () => {
  // //保证全部表单相校验通过再发请求
  await registerForm.value.validate()
  try {
    const { message, data } = await reqUerRegister(registerFormData)
    //pinia仓库存储一下token
    //由于pinia|vuex存储数据其实利用js对象
    let token = data.token
    //本地存储持久化存储一份
    SET_TOKEN(token)
    userStore.token = token
    active.value++
    ElMessage.success(message)
  } catch (error) {
    //登录失败的提示信息
    ElMessage({
      type: 'error',
      message: (error as Error).message,
    })
  }
}

const submitEmailForm = async () => {
  // //保证全部表单相校验通过再发请求
  await registerEmailForm.value.validate()
  try {
    const { message } = await reqBindingEmail(registerEmailFormData)
    ElMessage.success(message)
    active.value++
  } catch (error) {
    //登录失败的提示信息
    ElMessage({
      type: 'error',
      message: (error as Error).message,
    })
  }
}

//主题颜色的设置
const setColor = () => {
  //通知js修改根节点的样式对象的属性与属性值
  const html = document.documentElement
  userStore.userInfo.colorTheme = userData.colorTheme
  html.style.setProperty('--el-color-primary', userData.colorTheme)
  html.style.setProperty('--el-color-primary-light-3', userData.colorTheme)
  html.style.setProperty('--el-color-primary-dark-2', userData.colorTheme)
}

// 使用defineEmits注册一个自定义事件
const emit = defineEmits(['closeDialog'])

const submitUserDataForm = async () => {
  await userDataForm.value.validate()
  try {
    const { message } = await reqAddUserInfo(userData)
    ElMessage.success(message)
    await userStore.getUserInfo()
    router.replace({ name: 'home' })
  } catch (error) {
    //登录失败的提示信息
    ElMessage({
      type: 'error',
      message: (error as Error).message,
    })
  }
}
</script>

<style scoped lang="scss">
.register-form {
  margin-top: 48px;
  display: flex;
  justify-content: center;
}
</style>
